//
//  firstVC.m
//  lyxluyou
//
//  Created by mmyy on 15/10/14.
//  Copyright (c) 2015年 mmyy. All rights reserved.
//

#import "firstVC.h"
#import "Seciondata.h"
#import "FirstItems.h"
#import "firstCell.h"
#import "UIImageView+AFNetworking.h"
#import "cityVC.h"
#import "xiangqingVC.h"
#import "RDVTabBarController.h"
@interface firstVC ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@end

@implementation firstVC
{
    UIView *_titleView;
    NSMutableArray *_dataSource;
    UITableView *_tableView;
    BOOL isfoget;//判断选择
    NSMutableArray *_headViewData;
    NSTimer *_timer;
    UIImageView *_bgImage;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    isfoget = YES;
    [self createloadDataImage];
    //创建titleView
    [self createTitleView];
    
    [self createTableView];
    //获取数据
    [self loadData];
    //创建tableView
}
-(void)createloadDataImage
{
    _bgImage = [loadImage loadImage];
    _bgImage.frame = CGRectMake((self.view.frame.size.width - 100) / 2.0, (self.view.frame.size.height - 100) / 2, 100, 100);
    [self.view addSubview:_bgImage];
    
}
#pragma mark -- 创建titleView
-(void)createTitleView
{
    _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    _titleView.backgroundColor = [UIColor clearColor];
    _titleView.layer.cornerRadius = 10;
    _titleView.layer.borderColor = [UIColor blackColor].CGColor;
    _titleView.layer.borderWidth = 1;
    _titleView.layer.masksToBounds = YES;
    _titleView.userInteractionEnabled = NO;
    self.navigationItem.titleView = _titleView;
    UIButton *forgetBt = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [forgetBt setTitle:@"外国旅游" forState:UIControlStateNormal];
    forgetBt.backgroundColor = [UIColor whiteColor];
    [forgetBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    forgetBt.tag = 11;
    [_titleView addSubview:forgetBt];
    UIButton *dalu = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 100, 30)];
    [dalu setTitle:@"内地旅游" forState:UIControlStateNormal];
    dalu.backgroundColor = [UIColor clearColor];
    [dalu setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_titleView addSubview:dalu];
    dalu.tag = 12;
    [forgetBt addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [dalu addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)buttonClick:(UIButton *)sender
{
    if (sender.tag == 11) {
        sender.backgroundColor = [UIColor whiteColor];
        [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        UIButton *button = (UIButton *)[_titleView viewWithTag:12];
        button.backgroundColor = [UIColor clearColor];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        isfoget = YES;
    
        [self loadData];
    }else {
        sender.backgroundColor = [UIColor whiteColor];
        [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        UIButton *button = (UIButton *)[_titleView viewWithTag:11];
        button.backgroundColor = [UIColor purpleColor];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        isfoget = NO;
        [self loadData];
    
    }
    [_dataSource removeAllObjects];
    [_tableView reloadData];
}

#pragma mark -- loadData
-(void)loadData
{
    [_timer invalidate];
    _timer = nil;
    _bgImage.hidden = NO;
    [self.view bringSubviewToFront:_bgImage];
    _dataSource = [NSMutableArray arrayWithCapacity:0];
    NSString *url = nil;
    if (isfoget) {
        url = firstUrl;
    }else {
        url = daluUrl;
    }
    [Funcation getWithURL:url success:^(id responseObject) {
        [FirstItems removeDataAll:NO];
        [Seciondata removeAllData];
        NSLog(@"Success");
        if (isfoget) {
            NSArray *elements = [responseObject objectForKey:@"elements"];
            for(int i = 1; i < elements.count - 1; i++)
            {
                NSDictionary *value = [elements objectAtIndex:i];
                Seciondata *secion = [Seciondata MR_createEntity];
                secion.title = [value objectForKey:@"title"];
                [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
                NSArray *firsts = [value objectForKey:@"data"];
                NSMutableArray *cell = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *first in firsts) {
                    FirstItems *items = [FirstItems firstItemsWithDict:first];
                    items.title = secion.title;
                    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
                    [cell addObject:items];
                }
                NSDictionary *data = @{@"Sec":secion, @"Cell":cell};
                [_dataSource addObject:data];
            }
            if (!_headViewData) {
                _headViewData = [NSMutableArray array];
                NSArray *array = [[elements objectAtIndex:0] objectForKey:@"data"];
                for (NSDictionary *disItem in array) {
                    FirstItems *item = [FirstItems firstItemsWithDict:disItem];
                    [_headViewData addObject:item];
                }
                [self createHeadView];
                _titleView.userInteractionEnabled = YES;

            }
        }else {
            NSString *title = [responseObject objectForKey:@"title"];
            Seciondata *secion = [Seciondata MR_createEntity];
            secion.title = title;
            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
            NSArray *data = [responseObject objectForKey:@"data"];
            NSMutableArray *cell = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *dataItem in data) {
                FirstItems *items = [FirstItems firstItemsWithDict:dataItem];
                items.title = secion.title;
                [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
                [cell addObject:items];
            }
            NSDictionary *dataS = @{@"Sec":secion, @"Cell":cell};
            [_dataSource addObject:dataS];

        }
        _bgImage.hidden = YES;
        [_tableView reloadData];
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:NO];
        _timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(autoChangeScorllView) userInfo:nil repeats:YES];
    } andFail:^(id error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"请求数据错误，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        _bgImage.hidden = YES;
        
    }];


}

#pragma mark -- createTableView
-(void)createTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorColor = [UIColor clearColor];
    _tableView.rowHeight = 200;
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.top).offset(0);
        make.bottom.equalTo(self.view.bottom).offset(0);
        make.left.equalTo(self.view.left).offset(0);
        make.right.equalTo(self.view.right).offset(0);
    }];

}
#pragma  mark -- createTableViewHeadView
-(void)createHeadView
{
    UIScrollView *scorllView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    scorllView.delegate = self;
    scorllView.pagingEnabled = YES;
    scorllView.backgroundColor = [UIColor darkGrayColor];
    _tableView.tableHeaderView = scorllView;
    scorllView.contentSize = CGSizeMake(self.view.frame.size.width * (_headViewData.count + 1), 150);
    for (int i = 0; i < _headViewData.count + 1; i++) {
        int j = i;
        if (i == _headViewData.count) {
            j = 0;
        }
        FirstItems *items = [_headViewData objectAtIndex:j];
        UIImageView *bgImage = [[UIImageView alloc] init];
        [bgImage setImageWithURL:[NSURL URLWithString:items.cover_s] placeholderImage:[UIImage imageNamed:@"define"]];
        bgImage.backgroundColor = [UIColor orangeColor];
        UIView *footView = [[UIView alloc] init];
        footView.backgroundColor = [UIColor blackColor];
        footView.alpha = 0.6;
        [bgImage addSubview:footView];
        UILabel *name = [[UILabel alloc] init];
        name.text = items.name;
        name.textColor = [UIColor redColor];
        name.font = [UIFont boldSystemFontOfSize:20];
        name.backgroundColor = [UIColor clearColor];
        [footView addSubview:name];
        [scorllView addSubview:bgImage];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pgChange:)];
        [bgImage addGestureRecognizer:tap];
        bgImage.userInteractionEnabled = YES;
        [bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(scorllView.top).offset(0);
            make.left.equalTo(scorllView.left).offset(i * scorllView.frame.size.width);
            make.bottom.equalTo(scorllView.bottom).offset(0);
            make.width.equalTo(scorllView.width);
            make.height.equalTo(scorllView.height);
            if (i == _headViewData.count) {
                make.right.equalTo(scorllView.right).offset(0);
            }
        }];
        [footView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(bgImage.bottom).offset(0);
            make.height.equalTo(30);
            make.left.equalTo(bgImage.left).offset(0);
            make.right.equalTo(bgImage.right).offset(0);
        }];
        [name mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(footView.top).offset(3);
            make.bottom.equalTo(footView.bottom).offset(3);
            make.left.equalTo(footView.left).offset(10);
            make.right.equalTo(footView.right).offset(50);
        }];
        
        
    }
}
-(void)pgChange:(UITapGestureRecognizer *)sender
{
    UIImageView *image = (UIImageView *)sender.view;
    NSInteger count = image.frame.origin.x / self.view.frame.size.width;
    FirstItems *items = [_headViewData objectAtIndex:count];
    xiangqingVC *vc = [xiangqingVC new];
    vc.vid = items.vid;
    vc.titleName = items.name;
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark -- autoChnageScorllView
-(void)autoChangeScorllView
{
    UIScrollView *scor = (UIScrollView *)_tableView.tableHeaderView;
    NSInteger currentC = scor.contentOffset.x / self.view.frame.size.width;
    if (currentC == _headViewData.count) {
        [scor setContentOffset:CGPointMake(0, 0) animated:NO];
    }else {
        currentC += 1;
        [scor setContentOffset:CGPointMake(currentC * self.view.frame.size.width, 0) animated:YES];
    }

}
#pragma mark -- scrollViewDeleggate
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x == _headViewData.count * self.view.frame.size.width) {
        scrollView.contentOffset = CGPointZero;
    }

}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_timer invalidate];
    _timer = nil;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(autoChangeScorllView) userInfo:nil repeats:YES];
    _timer = timer;
}
#pragma mark -- tableViewdelegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_dataSource[section] objectForKey:@"Cell"] count];

}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    firstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"firstCell" owner:nil options:nil] lastObject];
    }
    FirstItems *items = [[[_dataSource objectAtIndex:indexPath.section] objectForKey:@"Cell"] objectAtIndex:indexPath.row];
    [cell.bgImage setImageWithURL:[NSURL URLWithString:items.cover_s] placeholderImage:[UIImage imageNamed:@"define"]];
    cell.nameLabel.text = items.name;
    cell.nameLabel.adjustsFontSizeToFitWidth = YES;
    return cell;


}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    view.backgroundColor = [UIColor purpleColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
    Seciondata *sec = [[_dataSource objectAtIndex:section] objectForKey:@"Sec"];
    label.text = sec.title;
    label.font = [UIFont boldSystemFontOfSize:25];
    label.textColor = [UIColor whiteColor];
    label.adjustsFontSizeToFitWidth = YES;
    [view addSubview:label];
//    label.text = 
    
    return view;

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    cityVC *city = [[cityVC alloc] init];
    if (isfoget) {
        if ([[[[_dataSource objectAtIndex:indexPath.section] objectForKey:@"Sec"] title] isEqualToString:@"港澳台"]) {
            city.cityId = [NSString stringWithFormat:@"1/%@",[[[[_dataSource objectAtIndex:indexPath.section] objectForKey:@"Cell"] objectAtIndex:indexPath.row] vid] ];
        }else {
        city.cityId = [NSString stringWithFormat:@"1/%@",[[[[_dataSource objectAtIndex:indexPath.section] objectForKey:@"Cell"] objectAtIndex:indexPath.row] vid] ];
        }
    }else {
        city.cityId = [NSString stringWithFormat:@"3/%@",[[[[_dataSource objectAtIndex:indexPath.section] objectForKey:@"Cell"] objectAtIndex:indexPath.row] vid] ];
    
    }
    city.cityTitle = [[[[_dataSource objectAtIndex:indexPath.section] objectForKey:@"Cell"] objectAtIndex:indexPath.row] name];
   
    [self.navigationController pushViewController:city animated:YES];

}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.rdv_tabBarController setTabBarHidden:NO animated:NO];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [_timer invalidate];
    _timer = nil;
    [self.rdv_tabBarController setTabBarHidden:YES animated:NO];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
